import {message} from "ant-design-vue";
import router from "@/router/index.js";
import axios from "axios";

axios.defaults.timeout = 5000;

// 请求拦截器
axios.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem('token');
        if (token) {
            token = token.replace(/^"|"$/g, ''); // 匹配开头或结尾的引号并移除
            config.headers.Authorization = token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
)

// 响应拦截器
axios.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response && error.response.status === 401) {
            message.error("身份验证过期，请重新登录")
            localStorage.removeItem('token')
            router.replace('/login');
        }
    }
)

// 导出
export default axios;